package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpSession httpSession;

    //登录
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String, String> user) {
        //1.接收参数
        String username = user.get("username");
        String password = user.get("password");

        //2.调用service进行登录
        ResultInfo resultInfo = employeeService.login(username, password);

        //3.登录成功,将用户信息存入session域对象中
        Employee data = (Employee) resultInfo.getData();
        httpSession.setAttribute("SESSION_EMPLOYEE", data);

        //4.将结果返回给前端
        return resultInfo;
    }

    //退出登录
    @PostMapping("/employee/logout")
    public ResultInfo logout() {
        //1.清理session中的用户信息
        httpSession.invalidate();//注销当前用户的session,不会动其他的session
        //2.返回成功标识(1)
        return ResultInfo.success(null);
    }

    //查询用户
    @GetMapping("/employee/find")
    public ResultInfo findByName(String name) {
        //1.调用service查询
        List<Employee> employeeList = employeeService.findByName(name);
        //2.返回ResultInfo
        return ResultInfo.success(employeeList);

    }

    //新增用户
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee) {
        employeeService.save(employee);
        return ResultInfo.success(null);
    }
    //回显用户信息
    @GetMapping("/employee/{id}")
    public ResultInfo findByID(@PathVariable("id") Long id){
     Employee employee  = employeeService.findByID(id);
     return ResultInfo.success(employee);
    }

    //修改用户信息
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee){
        employeeService.update(employee);
        return ResultInfo.success(null);
    }
}
